﻿using System;
using System.Collections;
using System.Threading;
using OME.Storage;
using System.Net.Sockets;
using System.Text;
using System.Net;
using System.Collections.Generic;

namespace OME
{
    public class OrderProcessor
    {
        public string service;
        
        public BizDomain bizDomain;
        Queue msgQueue;
        Thread msgDispatcher;
        ManualResetEvent processSignaller;      
        IPAddress groupAddress;
        IPEndPoint mcastEP;
        IPEndPoint localEP = new IPEndPoint(IPAddress.Loopback, 20000);
        Socket tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        QuoteServer qs;
        

        public OrderProcessor(BizDomain domain, string wspName )
        {
            bizDomain = domain;
            groupAddress = IPAddress.Parse("224.5.6.7");
            mcastEP = new IPEndPoint(groupAddress, 30002);
            //Domain under which this order processor is assigned            
            //create a order queue
            msgQueue = Queue.Synchronized(new Queue());
            //create a event notification object
            //which notifies the enqueuing of a new order
            processSignaller = new ManualResetEvent(false);
            //create a dedicated thread to process the order stored 
            //in queue collection
            msgDispatcher = new Thread(new ThreadStart(ProcessQueue));
            //start the processing
            msgDispatcher.Start();
        }

        private void BuildOrder(string serv)
        {
        }
        public void EnQueue(object newOrder)
        {
            //Enqueue the order and signal the event object
            msgQueue.Enqueue(newOrder);
            processSignaller.Set();
        }

        private void ProcessQueue()
        {
           
            //start of order draining process
            while (true)
            {  
               //Console.WriteLine("listening for orders");
                //wait for signal notification 
                processSignaller.WaitOne(1000, false);
                //iterate through queue 
                while (msgQueue.Count > 0)
                {
                    //dequeue the order
                    Order order = msgQueue.Dequeue() as Order;
                    //submit it to order book for further processing
                    bizDomain.OrderBook.Process(order);
                }
               //if(bizDomain.qs != null)
                  bizDomain.qs.ReturnQuotes();

            }
        }        
    }
}
